//
//  SYKaoShiJuanDetailsView.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2019/4/26.
//  Copyright © 2019年 SanYi. All rights reserved.
//

#import "SYKaoShiJuanDetailsView.h"
#import "WMPhotoBrowser.h"


@interface SYKaoShiJuanDetailsView () <UITableViewDelegate,UITableViewDataSource>



@property (strong, nonatomic) UIImageView *bgImageView;
@property (strong, nonatomic) UITableView *curTableView;
@property (strong, nonatomic) NSMutableArray *dataListArr;
@property (strong, nonatomic) NSMutableArray *jiexiArr;//解析
@property (strong, nonatomic) WMPhotoBrowser *browser;


//@property ()

@end


@implementation SYKaoShiJuanDetailsView


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithHexString:@"#EEEEEE"];
        [self initSubView];
    }
    return self;
}
//fudao_close
- (void)initSubView {
    self.dataListArr = [NSMutableArray array];
    self.jiexiArr = [NSMutableArray array];
    _browser = [WMPhotoBrowser new];
    
    _browser.downLoadNeeded = YES;
    [self addSubview:_browser.view];
    [self addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(20);
        make.right.left.equalTo(self);
        make.height.mas_equalTo(45);
    }];
    //退出
    [self addSubview:self.chakanBtn];
    [self.chakanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topView.mas_centerY);
        make.right.equalTo(self.mas_right).offset(-25);
        make.width.height.mas_equalTo(40);
    }];
    

    
    
    
    
    [self addSubview:self.curTableView];
    [self.curTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom);
        make.left.equalTo(self.mas_left).offset(20);
        make.right.bottom.equalTo(self).offset(-20);
    }];
    self.curTableView.hidden = YES;
}

- (void)requestDataImageArr:(NSMutableArray *)imageArr {
    _browser.dataSource = imageArr;
    
}

- (void)setPathStr:(NSString *)pathStr {
    self.bgImageView.hidden = NO;
    pathStr = [pathStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self.bgImageView sd_setImageWithURL:[NSURL URLWithString:pathStr]];
    
    
    
}
//标题
- (SYTopView *)topView {
    if (!_topView) {
        _topView = [[SYTopView alloc] init];
        _topView.titleLab.text = @"试卷详情";

    }
    return _topView;
}

- (UITableView *)curTableView {
    if (!_curTableView) {
        _curTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _curTableView.delegate = self;
        _curTableView.dataSource = self;
        _curTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _curTableView.backgroundColor = [UIColor whiteColor];
        [_curTableView registerCellWithNIbNames:@[@"SYKSQuestionsTableViewCell"]];
    }
    return _curTableView;
}

- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
    }
    return _bgImageView;
}

- (UIButton *)chakanBtn {
    if (!_chakanBtn) {
        _chakanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        //        [_chakanBtn setTitle:@"查看试卷" forState:UIControlStateNormal];
        //        [_chakanBtn setTitleColor:[UIColorChange colorwithHexString:@"SELECTEDCOLOR"] forState:UIControlStateNormal];
        [_chakanBtn setImage:[UIImage imageNamed:@"fudao_close"] forState:UIControlStateNormal];
        _chakanBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_chakanBtn setTitleColor:SELECTEDCOLOR forState:0];
        [_chakanBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _chakanBtn;
}
- (void)backBtnClick {
    [UIView animateWithDuration:kAnimate animations:^{
        self.frame = CGRectMake(0, kScreen_HEIGHT, APP_WIDTH, APP_HEIGHT-20);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}


#pragma mark - 试卷
- (void)requestDataListTemplateId:(NSString *)templateId {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD mj_showMessage:nil toView:self];
    [SYRequestAPI yj_requestStatisticsServicePaperDetailTemplateId:templateId success:^(NSMutableArray *dataListArr) {
        [MBProgressHUD mj_hideHUDForView:self];
        if (dataListArr.count > 0) {
            weakSelf.curTableView.hidden = NO;
            weakSelf.dataListArr = dataListArr;
            [weakSelf fenjiejiexijieguo];
            [weakSelf.curTableView reloadData];
        } else {
            
        }
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        
        
    }];
    
}

- (void)requestPreperListTemplateId:(NSString *)templateId {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD mj_showMessage:nil toView:self];
    [SYRequestAPI yj_requestStatisticsServicePaperDetailTemplateId:templateId success:^(NSMutableArray *dataListArr) {
        [MBProgressHUD mj_hideHUDForView:self];
        if (dataListArr.count > 0) {
            weakSelf.curTableView.hidden = NO;
            weakSelf.dataListArr = dataListArr;
            [weakSelf fenjiejiexijieguo];
            [weakSelf.curTableView reloadData];
        } else {
            
        }
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        
        
    }];
    
}
//重组解析结果
- (void)fenjiejiexijieguo {
    
    for (SYPaperDetailModel *questionsModel in self.dataListArr) {
        NSString *jiexiHtml = @"";
        if (questionsModel.subQuestionsArr.count > 0) {
            
            for (NSInteger i = 0 ; i < questionsModel.subQuestionsArr.count ; i++) {
                SYDataSubQuestionsModel *model = questionsModel.subQuestionsArr[i];
                if (i == 0) {
                    jiexiHtml = model.rightAnswer;
                } else {
                    jiexiHtml = [NSString stringWithFormat:@"%@%@",jiexiHtml,model.rightAnswer];
                }
                
            }
            
            
        }
        [self.jiexiArr addObject:jiexiHtml];
        
    }
    
    
}


#pragma mark - tab

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataListArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //SYPaperDetailModel *questionsModel = self.dataListArr[section];
    NSString *htmle = self.jiexiArr[section];
    if (htmle.length > 0) {
        return 1;
    } else {
        return 0;
    }
    
//    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *htmle = self.jiexiArr[indexPath.section];
    
    NSAttributedString *attributed = [self attributedStringWithHTMLString:htmle];
    
    CGFloat height = [attributed  boundingRectWithSize:CGSizeMake(kScreen_WIDTH - 180 , CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
    CGFloat ht = 40;
    if (height < 100) {
        return height + 50+ht;
    } else if (height < 200) {
        return height + 100+ht;
    } else {
        return height + 150+ht;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    SYPaperDetailModel *questionsModel = self.dataListArr[indexPath.section];
//    SYDataSubQuestionsModel *model = questionsModel.subQuestionsArr[indexPath.row];
    SYKSQuestionsTableViewCell *questionsCell = [tableView dequeueReusableCellWithIdentifier:@"SYKSQuestionsTableViewCell" forIndexPath:indexPath];
//    NSString *htmlStr = nil;
//    if (model.analysis.length > 0) {
//        htmlStr = [NSString stringWithFormat:@"%@ 解析%@",model.rightAnswer,model.analysis];
//    } else {
//        htmlStr = [NSString stringWithFormat:@"%@",model.rightAnswer];
//    }
    NSString *htmle = self.jiexiArr[indexPath.section];
    if ([htmle containsString:@"img"]) {
        if ([htmle containsString:@"attached"]) {
            NSRange atta = [htmle rangeOfString:@"attached"];
            NSMutableString* str1=[[NSMutableString alloc]initWithString:htmle];
            [str1 insertString:@"http://webeditor.31waiyu.com/"atIndex:atta.location];
            htmle = (NSString *)str1;
        }
    }
    
    [questionsCell.webView loadHTMLString:htmle baseURL:[NSURL URLWithString:@"http://webeditor.31waiyu.com/"]];
    
    return questionsCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    SYPaperDetailModel *questionsModel = self.dataListArr[section];
    
    NSAttributedString *attributed = [self attributedStringWithHTMLString:[NSString stringWithFormat:@"%@",questionsModel.questionContent]];
    
     CGFloat height = [attributed  boundingRectWithSize:CGSizeMake(kScreen_WIDTH - 180 , CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
    if ([questionsModel.questionContent containsString:@"img"]) {
        height = 200;
    }
    
    if (height < 100) {
        return height + 50;
    } else if (height < 200) {
        return height + 100;
    } else {
        return height + 150;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SYKaoShiHeaderView *headerView = [[NSBundle mainBundle] loadNibNamed:@"SYKaoShiHeaderView" owner:nil options:nil].firstObject;
    SYPaperDetailModel *questionsModel = self.dataListArr[section];
    
    headerView.titleLab.text = [NSString stringWithFormat:@"题型：%@ 难度：%@  知识点：%@  题目分数:%@",questionsModel.questionType,questionsModel.difficultyLevel,questionsModel.knowledgePoint,questionsModel.questionScore];
//    NSAttributedString *attributed = [self attributedStringWithHTMLString:[NSString stringWithFormat:@"%@ %@",questionsModel.questionSerial,questionsModel.questionContent]];
//    headerView.countLab.attributedText = attributed;
    NSString *htmle = questionsModel.questionContent;
    if ([htmle containsString:@"img"]) {
        if ([htmle containsString:@"attached"]) {
            NSRange atta = [htmle rangeOfString:@"attached"];
            NSMutableString* str1=[[NSMutableString alloc]initWithString:htmle];
            [str1 insertString:@"http://webeditor.31waiyu.com/"atIndex:atta.location];
            htmle = (NSString *)str1;
        }
    }
    
//    [questionsCell.webView loadHTMLString:htmle baseURL:[NSURL URLWithString:@"http://webeditor.31waiyu.com/"]];
    [headerView.webView loadHTMLString:[NSString stringWithFormat:@"%@ %@",questionsModel.questionSerial,questionsModel.questionContent] baseURL:[NSURL URLWithString:@"http://webeditor.31waiyu.com/"]];
    
    
    return headerView;
}

//计算富文本高度
- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString{
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    NSAttributedString *attributed = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    return attributed;
}




@end




















